package com.vtb.utils;


import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.vtb.servlet.WtbException;

public class JdbcUtils {
	private static final Log log = LogFactory.getLog(JdbcUtils.class);
	private static DataSource ds = null;
	private static ThreadLocal<Connection> t = new ThreadLocal<Connection>();
	static {
		ds = new ComboPooledDataSource();
	}

	public static DataSource getDataSource() {
		return ds;
	}

	public static Connection getConnection() {		
		Connection conn = t.get();
		try {
			if (conn == null) {				
				conn = ds.getConnection();					
				conn.setAutoCommit(false);
				t.set(conn);				
			}
			return conn;
			
		} catch (SQLException e) {
			log.error("获取数据库连接异常：", e);
			throw new WtbException(e);
		}

	}

	public static void commit() {
		try {
			Connection conn = t.get();
			if (conn != null) {
				conn.commit();
			}
		} catch (SQLException e) {
			log.error("数据提交异常：：", e);
			throw new WtbException(e);
		}
	}

	public static void rollback() {
		try {
			Connection conn = t.get();
			if (conn != null) {
				conn.rollback();
				conn.commit();
			}
		} catch (SQLException e) {
			log.error("事务回滚异常：：", e);
			throw new WtbException(e);
		}
	}

	public static void close() {
		try {
			Connection conn = t.get();
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			log.error("关闭数据库连接异常：", e);
			throw new WtbException(e);
		} finally {
			t.remove();
		}
	}

}
